<template>
  <el-card class="box-card" style="border-right: none; border-bottom: none !important; border-top: none !important;border-radius: 0;">
      <div class="card-header">
        <span>管理员</span>
        <el-button type="primary" @click="dialogVisible = true">新增</el-button>
      </div>
      <el-form :inline="true" :model="formInline" class="form-inline">
      <el-form-item label="用户名">
        <el-input v-model="formInline.username" placeholder="用户名" clearable />
      </el-form-item>
      <el-form-item label="状态">
        <el-select
          v-model="formInline.state"
          placeholder="状态"
          clearable
        >
          <el-option label="全部" value="" />
          <el-option label="启用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchUserList">搜索</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
  </el-form>
  
  <el-table :data="userList" v-loading="loading" height="580px" style="width: 100%">
    <!-- 渲染用户名 -->
    <el-table-column prop="username" label="用户名" min-width="150" />

    <!-- 渲染头像 -->
    <el-table-column label="头像" min-width="150">
      <template #default="scope">
        <img :src="scope.row.avatar" alt="头像" style="width: 50px; height: 50px; border-radius: 50%;" />
      </template>
    </el-table-column>
     <!-- 性别 -->
     <el-table-column prop="sex_text" label="性别" min-width="150" />

    <!-- 渲染昵称 -->
    <el-table-column prop="nickname" label="昵称" min-width="150" />

    <!-- 渲染手机号 -->
    <el-table-column prop="phone" label="手机号" min-width="150" />

    <!-- 渲染状态 -->
    <el-table-column label="状态" min-width="100">
      <template #default="scope">
        <el-tag v-if="scope.row.status === 1" type="success">{{scope.row.status_text}}</el-tag>
        <el-tag v-else type="danger">{{scope.row.status_text}}</el-tag>
      </template>
    </el-table-column>

    <!-- 渲染创建时间 -->
    <el-table-column prop="created_at" label="创建时间" width="160" />

    <!-- 渲染更新时间 -->
    <el-table-column prop="updated_at" label="更新时间" width="160" />

    <!-- 操作 -->
    <el-table-column fixed="right" label="操作" width="200" >
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        <el-button size="small" @click="handleView(scope.$index, scope.row)">查看</el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination class="el-p"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-card>

  <!-- 新增/编辑管理员对话框 -->
  <el-dialog
    v-model="dialogVisible"
    :title="dialogType === 'add' ? '新增管理员' : '编辑管理员'"
    width="500px"
    :close-on-click-modal="false"
  >
    <AddAdminUserForm ref="addFormRef" :form-data="currentFormData" :is-edit="dialogType === 'edit'" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 查看详情抽屉 -->
  <el-drawer
    v-model="drawerVisible"
    title="管理员详情"
    direction="rtl"
    size="50%"
  >
    <el-descriptions :column="1" border>
      <el-descriptions-item label="用户名">{{ currentFormData?.username }}</el-descriptions-item>
      <el-descriptions-item label="昵称">{{ currentFormData?.nickname }}</el-descriptions-item>
      <el-descriptions-item label="手机号">{{ currentFormData?.phone }}</el-descriptions-item>
      <el-descriptions-item label="状态">
        <el-tag :type="currentFormData?.status === 1 ? 'success' : 'danger'">
          {{ currentFormData?.status === 1 ? '启用' : '禁用' }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="创建时间">{{ currentFormData?.created_at }}</el-descriptions-item>
      <el-descriptions-item label="更新时间">{{ currentFormData?.updated_at }}</el-descriptions-item>
    </el-descriptions>
  </el-drawer>
</template>
<script setup>
  import { ref,reactive, watch } from 'vue';
  import { adminUserService } from '@/api/adminUser';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import AddAdminUserForm from '@/components/AddAdminUserForm.vue';

  const currentPage = ref(1)  // 默认第一页
  const pageSize = ref(10)    // 默认每页10条
  const small = ref(false)
  const background = ref(false)
  const disabled = ref(false)
  const userList = ref([])
  const dialogVisible = ref(false);
  const drawerVisible = ref(false);
  const addFormRef = ref(null);
  const dialogType = ref('add');
  const currentFormData = ref(null);
  const total = ref(0);
  const loading = ref(false);
  const formInline = reactive({
    username: '',
    state: ''
  });

  // 获取用户列表数据
  const fetchUserList = async () => {
    loading.value = true;
    try {
      const params = {
        username: formInline.username,
        status: formInline.state,
        page: currentPage.value,
        pageSize: pageSize.value
      };
      const response = await adminUserService.getList(params);
      userList.value = response.data || [];
      total.value = response.total || 0;
    } catch (error) {
      ElMessage.error('获取用户列表失败');
      userList.value = [];
      total.value = 0;
    }
    loading.value = false;
  };

  const handleEdit = (index, row) => {
    dialogType.value = 'edit';
    currentFormData.value = { ...row };
    dialogVisible.value = true;
  }
  /**
   * 处理删除管理员的操作
   * @param {Object} row - 包含管理员信息的对象，用于标识要删除的管理员
   */
  const handleDelete = async (row) => {
    try {
      // 弹出确认对话框，询问用户是否确定要删除指定的管理员
      await ElMessageBox.confirm(
        `确定要删除管理员 ${row.username} 吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      );
      
      // 调用后端接口删除指定ID的管理员
      await adminUserService.del(row.id);
      ElMessage.success('删除成功');
      // 重新获取用户列表数据
      fetchUserList();
    } catch (error) {
      // 处理删除过程中可能出现的错误
      // if (error !== 'cancel') {
      //   // 如果用户没有取消操作，则显示删除失败的错误提示
      //   ElMessage.error('删除失败');
      // }
    }
  };
  const handleView = (index, row) => {
    currentFormData.value = { ...row };
    drawerVisible.value = true;
  };

  // 每页条数变化
  const handleSizeChange = (size) => {
    pageSize.value = size;
    currentPage.value = 1; // 重置到第一页
    fetchUserList();
  };

  // 页码变化
  const handleCurrentChange = (page) => {
    currentPage.value = page;
    fetchUserList();
  };


  // 重置表单
  const resetForm = () => {
    formInline.username = '';
    formInline.state = '';
  };

    /**
   * 提交表单函数
   * 此函数用于处理管理员添加或更新表单的提交逻辑
   * 它首先验证表单数据的合法性，然后根据dialogType的值决定是添加还是更新管理员信息
   * 添加或更新操作成功后，会显示成功消息并刷新用户列表
   */
  const submitForm = async () => {
    // 检查表单引用是否存在
    if (!addFormRef.value) return;
    
    // 验证表单数据合法性
    const isValid = await addFormRef.value.validateForm();
    // 如果表单数据不合法，则终止操作
    if (!isValid) return;
    
    try {
      // 复制表单数据
      const formData = { ...addFormRef.value.form };
      
      // 根据dialogType的值决定是添加还是更新管理员信息
      if (dialogType.value === 'add') {
        // 添加管理员
        formData.id = null; // 确保添加时没有ID
        await adminUserService.addAdmin(formData);
        ElMessage.success('新增管理员成功');
      } else {
        // 更新管理员信息
        await adminUserService.updateAdmin(formData.id,formData);
        ElMessage.success('更新管理员成功');
      }
      
      // 关闭对话框
      dialogVisible.value = false;
      // 刷新用户列表
      fetchUserList();
    } catch (error) {
      // 处理添加或更新操作失败的情况
      //ElMessage.error(dialogType.value === 'add' ? '新增管理员失败' : '更新管理员失败');
    }
  };

  // 重置对话框状态
  const resetDialog = () => {
    dialogType.value = 'add';
    currentFormData.value = null;
    if (addFormRef.value) {
      addFormRef.value.resetForm();
    }
  };

  // 监听对话框关闭事件
  watch(dialogVisible, (newVal) => {
    if (!newVal) {
      resetDialog();
    }
  });

  
  // 初始化时获取用户列表
  fetchUserList();
  
</script>
<style scoped>
  .form-inline {
    margin: 20px 0;
    border-bottom: 1px solid #e4e7ed;
  }
  .el-p{
    margin-top: 15px;
    display: flex;
    justify-self: flex-end;
  }
  .el-select{
    width: 85px;
  }
  .card-header{
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 50px;
    border-bottom: 1px solid #a8aaad;
    
  }
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
  .el-descriptions {
    margin: 20px;
  }
</style>